package main

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"tg-bot/common"
	"tg-bot/common/telegram"
	"tg-bot/config"
	"tg-bot/middleware"
	"tg-bot/model"
	"tg-bot/rabbitmq"
	"tg-bot/router"
)

func main() {
	//common.InitSecretKey()
	//common.ConfigDetailEncrypt("test:Wechat73928487.@tcp(127.0.0.1:3306)/subfg_cn")
	config.InitConf()
	common.SetupLogger()

	model.SetupDB()
	defer model.CloseDB()

	config.InitRedisClient()

	rabbitmq.InitRabbitMQConfig()
	defer rabbitmq.CloseMQConnection()

	telegram.InitTelegramBo()

	initSync()
	common.SysLog("TG Bot" + common.VESRION + " started")

	initHttpServer()
}

func initHttpServer() {
	if viper.GetString("gin_mode") != "debug" {
		gin.SetMode(gin.ReleaseMode)
	}

	server := gin.New()
	server.Use(gin.Recovery())
	server.Use(middleware.RequestId())
	middleware.SetUpLogger(server)

	router.SetRouter(server)
	port := viper.GetString("port")
	err := server.Run(":" + port)
	if err != nil {
		common.FatalLog("failed to start HTTP server: " + err.Error())
	}
	common.SysLog("http server start success, services port is" + port)
}

func initSync() {
	go telegram.ListenTGBOMessage()
}
